虽然Google官方强烈建议我们视图应该在配置文件中定义,但是我们依然得掌握使用代码来控制布局文件。
15 代码控制Layout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.xianxiaotao.layout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new LinearLayout(this);
rootView.setOrientation(LinearLayout.VERTICAL);
setContentView(rootView);
for (int i = 0; i < 5; i++) {
Button button = new Button(this);
button.setAllCaps(false);
button.setText("Click To Remove Me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rootView.removeView(v);
}
});
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT );
lp.weight = 1;
rootView.addView(button, lp);
}
}
}